// pages/account/bankcard/bankcard.js
let common = require('../../../utils/common');
Page({
  data: {
    banks: [{ code: 'CDB', name: '农业银行' }, { code: 'ICBC', name: '工商银行' }, { code: 'KDC', name: '建设银行' }],
    index: 0,
    info: {}
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    if (options.info) {
      var info = JSON.parse(options.info);
      this.renderBank(info);
    }
  },
  renderBank(info) {
    var idx = 0;
    this.data.banks.filter((b, i) => {
      if (b.code == info.bankName){
        idx = i;
        return b;
      }
    });
    this.setData({
      info: info,
      index:idx
    });
  },
  bankChange(e) {
    let that = this, index = e.detail.value;
    that.setData({ index: parseInt(index) });
  },
  bankHandle(e) {
    let that = this;
    var info = that.formData(e.detail.value);
    common.asynPost(common.API.user.bankEdit, info, (data) => {
      if (data['id'] > 0) {
        wx.showToast({
          title: '保存成功', complete() {
            wx.navigateBack({
              delta: 1, // 回退前 delta(默认为1) 页面
            })
          }
        });
      } else {
        wx.showToast({ title: '保存失败' });
      }
    }, (err) => {
      wx.showToast({ title: '保存失败' });
    });
  },
  formData(info) {
    if (info.name && info.cardNo) {
      var bank = this.data.banks[this.data.index];
      return { name: info.name, cardNo: info.cardNo, bankName: bank.name, bankCode: bank.code };
    }
    wx.showToast({ title: '请填写完整的信息', duration: 2000 })
    return null;
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})